"""
Description:
Author: 月间
Date: 2025-10-20 23:36:39
LastEditTime: 2025-10-20 23:36:41
LastEditors:
"""

# @Version        : 1.0
# @Update Time    : 2025/10/20 20:00
# @File           : helpers.py
# @IDE            : PyCharm
# @Desc           : 依赖模块的通用辅助函数
from typing import Optional, Tuple, TYPE_CHECKING, Any, Coroutine

from fastapi import HTTPException, Request

from authx.core.auth_logic_interface import AuthLogicProtocol
from authx.core.context import AuthContextManager
from authx.core.manager import AuthManager
from src.log import logger

if TYPE_CHECKING:
    from authx.core.auth_logic import AuthLogic


async def ensure_login(
    request: Request, user_type: str, token: Optional[str]
) -> tuple[AuthLogicProtocol, int | str | None, bool]:
    """统一的登录校验与上下文设置。

    返回 (auth_logic, login_id, is_admin)。
    """
    if not token:
        raise HTTPException(status_code=401, detail="未登录")

    # 设置上下文（token）供后续逻辑读取
    AuthContextManager.set_current_token(token)
    # 获取认证逻辑实例
    auth_logic = AuthManager.get_logic(user_type)
    if not auth_logic:
        raise HTTPException(status_code=401, detail="登录类型错误")

    # 登录状态校验
    if not await auth_logic.is_login():
        logger.warning(f"未登录{token} {user_type}")
        raise HTTPException(status_code=401, detail="未登录")

    # 尽量基于token解析登录ID，避免依赖隐式上下文
    login_id = await auth_logic.get_login_id_by_token(token)
    is_admin = await auth_logic.is_super_admin()

    # 写入request.state，供路由或中间件使用
    request.state.login_type = user_type
    request.state.login_id = login_id

    return auth_logic, login_id, is_admin
